package com.example.boot.security.config;


import com.example.boot.security.filter.CheckTokenFilter;
import com.example.boot.security.handler.CustomerAccessDeniedHandler;
import com.example.boot.security.handler.LoginFailureHandler;
import com.example.boot.security.handler.LoginSuccessHandler;
import com.example.boot.security.handler.UnauthorizedEntryPoint;
import com.example.boot.service.impl.CustomerUserDetailsServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.annotation.Resource;

/**
 * @description:
 * @author: mhpy
 * @date 2022/8/5 21:02
 */
@Configuration
@EnableWebSecurity
//开启注解权限控制

@EnableGlobalMethodSecurity(prePostEnabled = true)
public class TokenWebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private CustomerUserDetailsServiceImpl customerDetailsServiceImpl;
    @Resource
    private LoginSuccessHandler loginSuccessHandler;
    @Resource
    private LoginFailureHandler loginFailureHandler;
    @Resource
    private UnauthorizedEntryPoint unauthorizedEntryPoint;
    @Resource
    private CustomerAccessDeniedHandler customerAccessDeniedHandler;
    @Resource
    private CheckTokenFilter checkTokenFilter;

//  security 加密  采用SHA-256 +随机盐+密钥对密码进行加密  不可逆

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
//    跨域

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("http://localhost:9538");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }
    /**
     * 配置设置
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        登录前过滤
        http.addFilterBefore(checkTokenFilter, UsernamePasswordAuthenticationFilter.class);
        http.formLogin()  //表单登录
                .loginProcessingUrl("/api/user/login")
                //登录url
                .usernameParameter("name")
                //前端传参数名 默认username
                .passwordParameter("password")
                //前端传密码名
                .successHandler(loginSuccessHandler)
                //认证成功
                .failureHandler(loginFailureHandler)
                //认证失败
                .and()
                .csrf().disable()
                                                                //不创建session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 未登录拦截
                .antMatchers("/api/user/login").permitAll()
                //登录放行
                .anyRequest().authenticated()  //拦截其他所有
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(unauthorizedEntryPoint)
                //匿名无权限访问
                .accessDeniedHandler(customerAccessDeniedHandler)
                //认证用户无权限
                .and().cors();  //支持跨域
    }
    /**
     * 密码处理
     * @param auth
     * @throws Exception
     */

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customerDetailsServiceImpl).passwordEncoder(passwordEncoder());
    }

    /**
     * 配置哪些请求不拦截
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
//        web.ignoring().antMatchers("/api/**",
//                "/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**"
//        );
//        web.ignoring().antMatchers("/*/**"
//       );
    }
}
